<template>
  <div class="my-appointments">
    <TopHeader />
    <BottomNavigation />
    <div class="page-header">
      <h2>我的预约</h2>
    </div>
    <el-empty v-if="loading === false && appointments.length === 0" description="暂无预约记录" />
    <div v-else>
      <el-card
        v-for="item in appointments"
        :key="item.id"
        class="appointment-card"
        shadow="hover"
      >
        <div class="card-header">
          <div>
            <span class="doctor">{{ doctorNameMap[item.docId] || item.docId }} - {{ item.docTitle || '' }}</span>
            <span class="dept">科室：{{ departmentNameMap[item.departId2] || item.departmentName2 || item.departId2 || '未知科室' }}</span>
          </div>
          <template v-if="item.diagnosisStatus == 0">
            <el-button
              type="danger"
              size="small"
              plain
              @click="cancelAppointment(item.id)"
              class="cancel-btn"
            >取消预约</el-button>
          </template>
          <template v-else>
            <span style="color:#52c41a;font-weight:bold;">已就诊</span>
          </template>
        </div>
        <div class="card-body">
          <div><b>预约日期：</b>{{ item.day }}</div>
          <div><b>预约时段：</b>{{ item.info }}</div>
          <div><b>联系电话：</b>{{ item.telephone }}</div>
          <div><b>备注：</b>{{ item.info }}</div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import TopHeader from '@/components/TopHeader.vue'
import BottomNavigation from '@/components/BottomNavigation.vue'

const userStore = useUserStore()
const appointments = ref([])
const loading = ref(true)

// 新增：医生id到姓名的映射
const doctorNameMap = ref({})
// 新增：科室id到科室名的映射
const departmentNameMap = ref({})

const fetchDoctors = async () => {
  const res = await axios.get('http://localhost:8080/hospital5_war/doctor/findAll')
  doctorNameMap.value = {}
  for (const doc of res.data) {
    doctorNameMap.value[doc.doc_id] = doc.doc_name
  }
}

const fetchDepartments = async () => {
  const res = await axios.get('http://localhost:8080/hospital5_war/department/findAll')
  departmentNameMap.value = {}
  for (const dept of res.data) {
    departmentNameMap.value[dept.departmentId] = dept.departmentName
  }
}

const fetchAppointments = async () => {
  loading.value = true
  try {
    // 获取所有预约，筛选当前用户
    const res = await axios.get('http://localhost:8080/hospital5_war/patientDoctor/findAll')
    const userId = userStore.userInfo?.userId
    appointments.value = (res.data || []).filter(item => item.patientId == userId)
    console.log('appointments', appointments.value) // 调试用
  } catch (e) {
    appointments.value = []
  } finally {
    loading.value = false
  }
}

const cancelAppointment = async (id) => {
  try {
    await ElMessageBox.confirm('确定要取消该预约吗？', '提示', { type: 'warning' })
    await axios.delete(`http://localhost:8080/hospital5_war/patientDoctor/deletePatientDoctor/${id}`)
    ElMessage.success('取消成功')
    fetchAppointments()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('取消失败')
  }
}

onMounted(() => {
  fetchDoctors()
  fetchDepartments()
  fetchAppointments()
})
</script>

<style scoped>
.my-appointments {
  padding: 15px;
  padding-top: 70px;
  padding-bottom: 70px;
  background: #f5f7fa;
  min-height: 100vh;
}
.page-header {
  margin-bottom: 15px;
  text-align: center;
}
.appointment-card {
  margin-bottom: 18px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(22,93,255,0.08);
  transition: box-shadow 0.3s;
}
.card-header {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.card-header .doctor {
  color: #165DFF;
  margin-right: 10px;
}
.card-header .dept {
  color: #888;
  font-size: 14px;
}
.cancel-btn {
  margin-left: 10px;
}
.card-body {
  font-size: 15px;
  color: #555;
  background: #f8faff;
  border-radius: 8px;
  padding: 10px 12px;
  margin-top: 6px;
}
</style>
